package com.wkck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wkck.VO.CompanyAllInfoListByIdsDto;
import com.wkck.VO.CompanyInfoVo;
import com.wkck.VO.CompanyVo;
import com.wkck.VO.PageResult;
import com.wkck.annotaion.ClearAllCache;
import com.wkck.domain.*;
import com.wkck.dto.CompanyQueryParamsDto;
import com.wkck.dto.SaveCompanyInfoDto;
import com.wkck.exception.BaseException;
import com.wkck.mapper.*;
import com.wkck.service.CompanyService;
import com.wkck.service.JobJoinService;
import com.wkck.service.JobService;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: CK
 * @Date: 2023/12/22/21:34
 * @Description:
 */
@Service
@Slf4j
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private CompanyPhotoMapper companyPhotoMapper;

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucket;

    @Autowired
    private JobJoinService jobJoinService;

    @Autowired
    private JobJoinMapper jobJoinMapper;

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private JobService jobService;

    @Autowired
    private DeliveredLibraryMapper deliveredLibraryMapper;


    /**
     * @Author: CK
     * @Date: 2024/2/8
     * @Param: [companyQueryParamsDto]
     * @Description: 得到所有公司完整信息
     */
    @Override
    public PageResult getAllCompanyInfo(CompanyQueryParamsDto companyQueryParamsDto) {

        PageHelper.startPage(companyQueryParamsDto.getPageNum(), companyQueryParamsDto.getPageSize());

        Page<CompanyInfoVo> allCompanyInfo = companyMapper.getAllCompanyInfo(companyQueryParamsDto);

        return PageResult.builder()
                .total(allCompanyInfo.getTotal())
                .records(allCompanyInfo)
                .build();
    }

    /**
    * @Author: CK
    * @Date: 2024/2/9
    * @Description: 清理缓存
    */
    @Override
    @ClearAllCache
    public Boolean clearCache() {
        return true;
    }

    /**
    * @Author: CK
    * @Date: 2024/2/10
    * @Param: [saveCompanyInfoDto]
    * @Description: 保存公司信息
    */
    @Override
    @Transactional
    public Boolean saveCompanyInfo(SaveCompanyInfoDto saveCompanyInfoDto) {

        List<String> allCompanyName = companyMapper.getAllCompanyName();

        boolean contains = allCompanyName.contains(saveCompanyInfoDto.getCompany());
        if (contains) {
            throw new BaseException("公司名称已存在，请重新输入！");
        }

        Company company = new Company();
        BeanUtils.copyProperties(saveCompanyInfoDto, company);

        List<String> countrys = saveCompanyInfoDto.getCountry();
        StringBuffer stringBuffer = new StringBuffer();
        countrys.forEach(country -> stringBuffer.append(country));
        company.setAddress(stringBuffer.toString());

        companyMapper.insert(company);
        log.info("添加成功");
        return true;
    }

    /***
    * @Author: CK
    * @Date: 2024/2/11
    * @Param: [uuid]
    * @Description: 根据uuid获取公司信息
    */
    @Override
    public CompanyInfoVo getCompanyInfoByUUID(String uuid) {
        if (uuid == null) {
            throw new BaseException("UUID为空！");
        }
        return companyMapper.getCompanyInfoByUUID(uuid);
    }

    /***
    * @Author: CK
    * @Date: 2024/2/11
    * @Param: [ids]
    * @Description: 批量删除公司信息
    */
    @Override
    @Transactional
    public Boolean removeCompanyInfoByIds(List<Integer> ids) {
        if (ids.isEmpty()) {
            throw new BaseException("id为空 不允许进行操作");
        }

        LambdaQueryWrapper<CompanyPhoto> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CompanyPhoto::getCompany_id, ids);
        List<CompanyPhoto> companyPhotos = companyPhotoMapper.selectList(queryWrapper);
        if (companyPhotos.isEmpty()) {
            companyMapper.deleteBatchIds(ids);
            return true;
        }

        // 将文件从minio中删除
        log.info("将文件从minio中删除");
        companyPhotos.forEach(companyPhoto -> {
            String location = companyPhoto.getLocation();

            try {
                minioClient.removeObject(
                        RemoveObjectArgs.builder()
                                .bucket(bucket)
                                .object(location)
                                .build()
                );
            } catch (Exception e) {
                throw new BaseException("文件删除异常！");
            }
        });

        log.info("删除photo列表");
        LambdaQueryWrapper<CompanyPhoto> photoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        photoLambdaQueryWrapper.in(CompanyPhoto::getCompany_id, ids);
        companyPhotoMapper.delete(photoLambdaQueryWrapper);

        log.info("删除公司信息");
        companyMapper.deleteBatchIds(ids);
        return true;
    }

    @Override
    @Transactional
    public Boolean modifyCompanyInfo(SaveCompanyInfoDto saveCompanyInfoDto) {

        CompanyInfoVo info = companyMapper.getCompanyInfoByUUID(saveCompanyInfoDto.getUuid());
        log.info("{}", info);

        String beforeCompanyName = info.getCompany();
        if (Objects.isNull(info)) {
            throw new BaseException("未找到公司信息 不允许修改！");
        }

        if ("".equals(saveCompanyInfoDto.getUuid())) {
            throw new BaseException("未找到公司UUID 不允许修改！");
        }

        List<String> countrys = saveCompanyInfoDto.getCountry();
        StringBuffer stringBuffer = new StringBuffer();
        countrys.forEach(country -> stringBuffer.append(country));

        if (info.getCompany().equals(saveCompanyInfoDto.getCompany())) {

            conditionGenertor(saveCompanyInfoDto, stringBuffer, beforeCompanyName);

        } else {
           throw new BaseException("公司名称不允许修改！");
        }

        return true;
    }

    /***
     * @Author: CK
     * @Date: 2024/2/12
     * @Param: [id, state]
     * @Description: 修改公司状态
     */
    @Override
    @ClearAllCache
    public Boolean updateCompanyState(Integer id, Integer state) {
        if (id == null || state == null) {
            throw new BaseException("id和状态不能为空！");
        }
        LambdaUpdateWrapper<Company> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .set(Company::getState, state)
                .eq(Company::getId, id);

        update(updateWrapper);
        return true;
    }

    /***
    * @Author: CK
    * @Date: 2024/2/12
    * @Param: [ids]
    * @Description: 公司信息详情
    */
    @Override
    public List<CompanyAllInfoListByIdsDto> getCompanyInfoByIds(List<Integer> ids) {

        List<CompanyAllInfoListByIdsDto> list = new ArrayList<>();
        for (Integer id : ids) {

            CompanyInfoVo companyInfoVos = companyMapper.getAllCompanyInfoByIds(id);
            String company = companyInfoVos.getCompany();
            log.info("over ===========> 1");

            List<Integer> job_ids = jobJoinMapper.getJobIds(company);
            log.info("over ===========> 2");

            List<Job> jobByIds = null;
            if (!job_ids.isEmpty()) {
                jobByIds = jobMapper.getJobByIds(job_ids);
                log.info("over ===========> 3");
            }

            CompanyAllInfoListByIdsDto listByIdsDto = CompanyAllInfoListByIdsDto.builder()
                    .companyInfoVos(companyInfoVos)
                    .jobs(jobByIds)
                    .build();

            list.add(listByIdsDto);
        }

        return list;
    }

    /**
     * @Author: CK
     * @Date: 2024/3/16
     * @Param: [company]
     * @Description: 根据公司名称获得公司信息
     */
    @Override
    public CompanyVo getCompanyVo(String company) {
        if (Strings.isEmpty(company)) {
            throw new BaseException("获取公司信息异常！");
        }

        CompanyVo vo = companyMapper.getCompanyVO(company);

        LambdaQueryWrapper<Job_join> jjWrapper = new LambdaQueryWrapper<>();
        jjWrapper.eq(Job_join::getCompany, company);

        Integer count = jobJoinMapper.selectCount(jjWrapper);
        vo.setCount(count);

        return vo;
    }

    public void conditionGenertor(SaveCompanyInfoDto saveCompanyInfoDto, StringBuffer stringBuffer, String beforeCompanyName) {
        LambdaUpdateWrapper<Company> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .set(Strings.isNotEmpty(saveCompanyInfoDto.getCompany()) ,Company::getCompany, saveCompanyInfoDto.getCompany())
                .set(Strings.isNotEmpty(saveCompanyInfoDto.getEmail()), Company::getEmail, saveCompanyInfoDto.getEmail())
                .set(Strings.isNotEmpty(saveCompanyInfoDto.getScale()), Company::getScale, saveCompanyInfoDto.getScale())
                .set(Strings.isNotEmpty(saveCompanyInfoDto.getPhone()), Company::getPhone, saveCompanyInfoDto.getPhone())
                .set(Strings.isNotEmpty(saveCompanyInfoDto.getPrincipal()), Company::getPrincipal, saveCompanyInfoDto.getPrincipal())
                .set(Strings.isNotEmpty(saveCompanyInfoDto.getState().toString()),Company::getState, saveCompanyInfoDto.getState())
                .set(Strings.isNotEmpty(saveCompanyInfoDto.getStart_time()), Company::getStart_time, saveCompanyInfoDto.getStart_time())
                .set(Company::getAddress, stringBuffer.toString())
                .eq(Company::getUuid,saveCompanyInfoDto.getUuid());

        update(updateWrapper);

        Job_join jobJoin = new Job_join();
        BeanUtils.copyProperties(saveCompanyInfoDto, jobJoin);
        log.info("{}", jobJoin);

        LambdaUpdateWrapper<Job_join> jobJoinLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        jobJoinLambdaUpdateWrapper
                .set(Strings.isNotEmpty(jobJoin.getCompany()) ,Job_join::getCompany, jobJoin.getCompany())
                .set(Strings.isNotEmpty(jobJoin.getEmail()), Job_join::getEmail, jobJoin.getEmail())
                .set(Strings.isNotEmpty(jobJoin.getPhone()), Job_join::getPhone, jobJoin.getPhone())
                .set(Strings.isNotEmpty(jobJoin.getPrincipal()), Job_join::getPrincipal, jobJoin.getPrincipal())
                .set(Strings.isNotEmpty(jobJoin.getStart_time()), Job_join::getStart_time, jobJoin.getStart_time())
                .eq(Strings.isNotEmpty(jobJoin.getCompany()) ,Job_join::getCompany, beforeCompanyName);

        jobJoinService.update(jobJoinLambdaUpdateWrapper);
    }
}
